--- 模块功能：拨打电话模块
-- @author miuser
-- @module elderphone.call
-- @license MIT
-- @copyright miuser
-- @release 2020-05-15

module(...,package.seeall)
require"cc"
require"audio"
require"pins"
require"utils"
require"pm"
require"common"

--当前拨叫号码
local s_currcallingnumber=0

--- “通话已建立”消息处理函数
-- @string num，建立通话的对方号码
-- @return 无
local function connected(num)
    log.info("testCall.connected")
    write("电话接通")
    --发送DTMF到对端
    --cc.sendDtmf("123")
    --5秒后播放TTS给对端，底层软件必须支持TTS功能
    --sys.timerStart(audio.play,5000,0,"TTSCC","通话中播放TTS测试",7)
    --50秒之后主动结束通话
    --sys.timerStart(cc.hangUp,50000,num)
end
sys.subscribe("CALL_CONNECTED",connected)

--- “通话已结束”消息处理函数
-- @return 无
local function disconnected()
    log.info("testCall.disconnected")
    write("通话断开")
    sys.timerStopAll(cc.hangUp)
end
sys.subscribe("CALL_DISCONNECTED",disconnected)

--- “来电”消息处理函数
-- @string num，来电号码
-- @return 无
local function incoming(num)
    log.info("testCall.incoming:"..num)
    --接听来电
    --cc.accept(num)
    s_currcallingnumber=num
    write("有来电，号码为"..num)
end
sys.subscribe("CALL_INCOMING",incoming)

--- “通话功能模块准备就绪””消息处理函数
-- @return 无
local function ready()
    write("已联网")
end
sys.subscribe("NET_STATE_REGISTERED",ready)

local function ccall(s_TEL)
    log.info("calling.out","calling",s_TEL)
    cc.dial(s_TEL)
    s_currcallingnumber=s_TEL
    sys.publish("CALL OK",s_TEL)
end
sys.subscribe("CALL",ccall)


local function cover()
    log.info("Hunging up.No",s_currcallingnumber)
    cc.hangUp(s_currcallingnumber)
    sys.publish("OVER OK")
end
sys.subscribe("OVER",cover)


local function canswer()
    log.info("Answer.No",s_currcallingnumber)
    cc.accept(s_currcallingnumber)
    sys.publish("ANSWER OK")
end
sys.subscribe("ANSWER",canswer)

function write(s)
    log.info("elderphone.call",s)
    sys.publish("UARTOUT",s)
end
